﻿


CREATE PROCEDURE [dbo].[write_log]
	@SqlCommand varchar(8000),
	@SqlParam varchar(8000),
	@idLog bigint OUT
AS

BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @now datetime
	DECLARE @cmd varchar(8000)
	DECLARE @an varchar(4)
	DECLARE @luna varchar(2)
	DECLARE @numetabela varchar(200)
	SET @now = GETDATE()
	SET @an =  CAST(YEAR(@now) as varchar(4));
	SET @luna = LTRIM(RTRIM(CAST(MONTH(@now) as varchar(2))));

	IF LEN(@luna)=1
		SET @Luna = '0' + @luna;

	SET @numetabela  = N'[ESRP_log].[dbo].[log' +@an  + @luna + ']'
	
    -- Insert statements for procedure here
	IF NOT EXISTS (SELECT * FROM [ESRP_log].sys.objects WHERE object_id = OBJECT_ID(@numetabela)  AND type in (N'U'))
	BEGIN
		SET @cmd ='USE [ESRP_log];
		CREATE TABLE '+@numetabela +'(
			[ID] [bigint] IDENTITY(1,1) NOT NULL,
			[DataExecutie] [datetime] NOT NULL,
			[SQLCommand] [varchar](8000) NOT NULL,
			[SQLParam] [varchar](8000) NOT NULL,
			[UserName] [varchar](50) NOT NULL,
			[IPAddress] [varchar](200) NOT NULL,
			[Result] [int] NOT NULL,
			[ErrorMessage] [varchar](8000) NOT NULL,
		 CONSTRAINT [PK_log'+@an+@luna+'] PRIMARY KEY CLUSTERED ([ID] ASC)) '
		PRINT(@cmd)
		EXEC(@cmd)
		IF @@ERROR != 0 GOTO EROARE	
	END

	SET @cmd = 'INSERT INTO '+@numetabela +'
           ([DataExecutie]
           ,[SQLCommand]
		   ,[SQLParam]
           ,[UserName]
           ,[IPAddress]
           ,[Result]
           ,[ErrorMessage])
     VALUES
           (GETDATE()
           ,''' +@SqlCommand +'''
		   ,''' +@SqlParam +'''
           ,suser_sname()
           ,host_name()
           ,0
           ,'''')'
	PRINT(@cmd)
	EXEC(@cmd)

	IF @@ERROR != 0 GOTO EROARE	
	SET @idLog = @@IDENTITY 


	GOTO Gata
	EROARE:
		RAISERROR ('Eroare la salvarea in log datelor!',16,-1)
		GOTO Gata
	EROARE1:
		RAISERROR ('!!',16,-1)	
		GOTO Gata
	Gata:
END